package org.lanqiao.controller;

import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeWapPayModel;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.alipay.api.response.AlipayTradeWapPayResponse;
import org.lanqiao.config.AlipayConfig;
import org.lanqiao.entity.OrderInfo;
import org.lanqiao.entity.WapPayResponse;
import org.lanqiao.service.AliPayService;
import org.lanqiao.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

@Controller
public class AliPayController {
    @Autowired
    AlipayConfig alipayConfig;
    @Autowired
    AliPayService aliPayService;


    /**
     * @Author 任春旭
     * @Description //TODO 获取充值地址
     * @Date 2019/6/12 13:51
     * @Param userId    用户id
     * @Param money  充值金额
     * @return org.lanqiao.util.Result
     */
    @ResponseBody
    @GetMapping("/getPayUrl")
    public Result getPayUrl(String userId,String money){
        // 获取订单号
        String order = aliPayService.getOrderId(userId, money);
        // 返回充值路径
        return Result.ok(alipayConfig.topay_url+"?orderId="+order);
    }
    /**
     * @Author 任春旭
     * @Description //TODO 付款
     * @Date 2019/6/12 13:51
     * @Param orderId  订单id
     * @return org.lanqiao.util.Result
     */
    @RequestMapping("/toPay")
    public void toPay(HttpServletResponse httpResponse,String orderId) throws Exception {
        OrderInfo orderInfo =aliPayService.getPayInfoByOrderId(orderId);
        if(orderInfo==null){
            try{
                PrintWriter writer = httpResponse.getWriter();
                writer.write( "::::订单已失效::");
                writer.close();
            }catch (Exception e){
                e.printStackTrace();
            }
            return;
        }
        AlipayClient alipayClient = new DefaultAlipayClient(alipayConfig.URL,alipayConfig.APPID,alipayConfig.RSA_PRIVATE_KEY,alipayConfig.FORMAT,alipayConfig.CHARSET,alipayConfig.ALIPAY_PUBLIC_KEY,alipayConfig.SIGNTYPE);
        AlipayTradeWapPayRequest request = new AlipayTradeWapPayRequest();
        // 封装请求支付信息
        AlipayTradeWapPayModel model=new AlipayTradeWapPayModel();
        //商户网站唯一订单号
        model.setOutTradeNo(orderInfo.getOutTradeNo());
        //商品的标题/交易标题/订单标题/订单关键字等。
        model.setSubject(orderInfo.getSubject());
        //订单总金额，单位为元，精确到小数点后两位，取值范围[0.01,100000000]
        model.setTotalAmount(orderInfo.getTotalAmount());
        //对一笔交易的具体描述信息。如果是多种商品，请将商品描述字符串累加传给body。
        model.setBody(orderInfo.getBody());
        //该笔订单允许的最晚付款时间，逾期将关闭交易。取值范围：1m～15d。m-分钟，h-小时，d-天，1c-当天（1c-当天的情况下，无论交易何时创建，都在0点关闭）。 该参数数值不接受小数点， 如 1.5h，可转换为 90m。
        model.setTimeoutExpress(orderInfo.getTimeoutExpress());
        //销售产品码，商家和支付宝签约的产品码
        model.setProductCode(orderInfo.getProductCode());
        request.setBizModel(model);
        // 设置异步通知地址
        request.setNotifyUrl(alipayConfig.notify_url);
        // 设置同步地址
        request.setReturnUrl(alipayConfig.return_url);
        AlipayTradeWapPayResponse response = alipayClient.pageExecute(request);
        httpResponse.setContentType("text/html;charset=" + alipayConfig.CHARSET);
        httpResponse.getWriter().write(response.getBody());//直接将完整的表单html输出到页面
        httpResponse.getWriter().flush();
        httpResponse.getWriter().close();
        if(response.isSuccess()){
            System.out.println("调用成功");
        } else {
            System.out.println("调用失败");
        }
    }
    /**
     * @Author 任春旭
     * @Description //TODO
     * @Date 2019/6/12 13:51
     * @Param wapPayResponse  支付宝返回码
     * @return org.lanqiao.util.Result
     */
    @ResponseBody
    @RequestMapping("/notify")
    public void ajaxNotify(WapPayResponse wapPayResponse){
        System.out.println("服务器异步通知页面路径");
        System.out.println(wapPayResponse);
    }
    /**
     * @Author 任春旭
     * @Description //TODO  返回充值状态
     * @Date 2019/6/12 13:51
     * @Param wapPayResponse  支付宝返回码
     * @return org.lanqiao.util.Result
     */
    @RequestMapping("/sync")
    public void sync(HttpServletResponse response,WapPayResponse wapPayResponse){
        // 支付成功 去加钱
        aliPayService.recharge(wapPayResponse.getOut_trade_no());
        System.out.println("服务器同步通知页面路径");
        System.out.println(wapPayResponse);
        try{
            PrintWriter writer = response.getWriter();
            writer.write( "恭喜您充值成功^_^");
            writer.close();
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
